package com.sunshine.wrongquestionset.activity.add_question

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import com.sunshine.wrongquestionset.room.entity.*
import com.sunshine.wrongquestionset.room.repository.MyRepository

/**
 * @author sunshine
 * @date 2021/3/28
 */
class AddQuestionViewModel(application: Application): AndroidViewModel(application) {
    private val repository: MyRepository = MyRepository(application.applicationContext)

    /**
     * 获取所有可以选择的题型
     */
    fun getQuestionType(): LiveData<List<QuestionTypeEntity>?> {
        return repository.getAllQuestionType()
    }

    /**
     * 获取所有可以选择的错题集
     */
    fun getQuestionSet(userId: String, subjectId: Int): LiveData<List<QuestionSetEntity>?> {
        return repository.getQuestionSetBySubjectId(userId, subjectId)
    }

    /**
     * 获取所有可以选择的科目
     */
    fun getQuestionSubject(userId: String): LiveData<List<SubjectEntity>?> {
        return repository.getAllSubject(userId)
    }

    fun getSubjectById(subjectId: Int): LiveData<SubjectEntity?> {
        return repository.getSubjectById(subjectId)
    }

    fun toSaveQuestion(
        userId: String,
        questionSetId: Int,
        subjectId: Int,
        typeId: Int,
        tag: String,
        titlePath: String,
        answerPath: String,
        familiarity: Float,
        difficulty: Float,
        lastTime: Long,
        doCount: Int,
        note: String?,
        insertTime: Long,
        score: Float,
        updateTime: Long
    ) {
        repository.insertQuestion(userId, questionSetId, subjectId, typeId, tag, titlePath, answerPath, familiarity, difficulty, lastTime, doCount, note, insertTime, score)
    }

    fun updateQuestion(questionEntity: QuestionEntity) {
        repository.updateQuestionByEntity(questionEntity)
    }

    fun toSaveQuestionInfo(owner: LifecycleOwner, familiarity: Float) {
        val lastQuestionLiveData = repository.getLastQuestion()
        lastQuestionLiveData.observe(owner, Observer {
            repository.insertQuestionInfo(it.id, familiarity)
            //每次保存完需要移除观察者，否则会添加多余项
            lastQuestionLiveData.removeObservers(owner)
        })
    }

    //2021 04 10 添加查询该用户所有科目
    fun getSubjectByUserId(userId: String): LiveData<List<SubjectEntity>?> {
        return repository.getAllSubject(userId)
    }

    fun addQuestionSet(userId: String, name: String, description: String?, subjectId: Int, backgroundColor: String) {
        repository.insertQuestionSet(userId, name, description, subjectId, backgroundColor)
    }
}